package com.hcrazy.manchester.app.services;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hcrazy.manchester.app.jdbc.AdvertDAO;
import com.hcrazy.manchester.app.jdbc.CouponDAO;
import com.hcrazy.manchester.app.jdbc.CouponSellerDAO;
import com.hcrazy.manchester.app.jdbc.UserDAO;
import com.hcrazy.manchester.app.pojo.Advert;
import com.hcrazy.manchester.app.pojo.Coupon;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.utils.Constant;

public class CouponService {

	private CouponDAO couponDAO;
	
	private UserDAO userDAO;
	
	private AdvertDAO advertDAO;
	
	public AdvertDAO getAdvertDAO() {
		return advertDAO;
	}

	public void setAdvertDAO(AdvertDAO advertDAO) {
		this.advertDAO = advertDAO;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public CouponDAO getCouponDAO() {
		return couponDAO;
	}

	public void setCouponDAO(CouponDAO couponDAO) {
		this.couponDAO = couponDAO;
	}
	
	private CouponSellerDAO couponSellerDAO;
	
	public CouponSellerDAO getCouponSellerDAO() {
		return couponSellerDAO;
	}

	public void setCouponSellerDAO(CouponSellerDAO couponSellerDAO) {
		this.couponSellerDAO = couponSellerDAO;
	}

	public ErrorMsg addOrUpdateCoupon(Coupon coupon) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		
		DateTime dt = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(coupon.getPublishDate());  
		if(null == coupon.getEndDate() || "".equals(coupon.getEndDate())){
			DateTime endDate = dt.plusDays(30);
			coupon.setEndDate(endDate.toString("yyyy-MM-dd"));
		}
		
		coupon.setSellerName(couponSellerDAO.getById(coupon.getSellerId()).getName());
		
		long couponId = 0;
		
		if(coupon.getCouponId() > 0){
			coupon.setPraiseCount(coupon.getPraiseCount() + coupon.getPraiseBaseCount());
			coupon.setCommentCount(coupon.getCommentCount() + coupon.getCommentBaseCount());
			couponDAO.updateCoupon(coupon);
			
			couponId = coupon.getCouponId();
		}else{
			if(null != coupon && coupon.getPraiseBaseCount() > 0){
				coupon.setPraiseCount(coupon.getPraiseBaseCount());
			}
			if(null != coupon && coupon.getCommentBaseCount() > 0){
				coupon.setCommentCount(coupon.getCommentBaseCount());
			}
			couponId = couponDAO.addCoupon(coupon);
		}
		
		if(coupon.getAdvertStr() != null && !coupon.getAdvertStr().equals("")){

			Gson gson = new Gson();
			Type type = new TypeToken<Advert>(){}.getType();
			Advert ad = gson.fromJson(coupon.getAdvertStr(),type);
			if(null != ad && ad.getAdContent() != null && !ad.getAdContent().equals("")){
				advertDAO.deleteAdvert(couponId,Constant.COMM_COUPON_INFO_MODULE);
				
				ad.setModuleId(couponId);
				ad.setModuleType(Constant.COMM_COUPON_INFO_MODULE);
				advertDAO.addAdvert(ad);
			}
			
		}
		
		return msg;
	}
	
	public PageModel getAllCoupons(PageModel model,String search,int sortId,int sellerId) throws Exception{
		return couponDAO.getPagedInfos(model, search, sortId,sellerId);
	}
	
	public PageModel getAllCoupons(PageModel model,String search,int sortId,int sellerId,long userId) throws Exception{
		return couponDAO.getPagedInfos(model, search, sortId,sellerId,userId);
	}
	
	public Coupon getInfoById(int infoId) throws Exception{
		Coupon coupon =  couponDAO.getById(infoId);
		Advert advert = advertDAO.getAdvert(infoId,Constant.COMM_COUPON_INFO_MODULE);
		if(null != advert)
			coupon.setAdvert(advert);
		return coupon;
	}
	
	public void delCoupon(int infoId) throws Exception{
		couponDAO.delCoupon(infoId);
	}
	
	public Object addUserCoupon(long userId,int couponId,String password) throws Exception{
		
		//判断卡包数量是否已满
		int bagCountMax = userDAO.getBagCount(userId);
		int bagCount = couponDAO.getCountByUserId(userId);
		
		if(bagCount >= bagCountMax){
			return new ErrorMsg(Constant.COUPON_ERROR_CODE_BAG_FULL, "卡包已满");
		}
		
		//判断是否领取过
		if(couponDAO.getCountByUserIdAndCouponId(userId, couponId) > 0){
			return new ErrorMsg(Constant.COUPON_ERROR_CODE_RECEIVED, "已领取");
		}
		String receiveTime = new DateTime().toString("yyyy-MM-dd HH:mm:ss");
		
		//获取优惠券类型，以确定是否凭密领取
		Coupon coupon = couponDAO.getById(couponId);
		if(coupon.getType() == Constant.COUPON_TYPE_LIMIT){
			//判断密码是否正确
			if(null == password || "".equals(password)){
				return new ErrorMsg(Constant.COUPON_ERROR_CODE_BY_PASSWORD, "此为限量版，请凭密领取！");
			}
			if(!coupon.getPassword().equals(password)){
				return new ErrorMsg(Constant.COUPON_ERROR_CODE_PASSWORD_ERROR, "密码错误！");
			}
		}
		
		couponDAO.addUserCoupon(userId, couponId, receiveTime);
		Map<String,String> result = new HashMap<String,String>();
		result.put(Constant.SINGLE_RETURN,"true");
		
		return result;
	}
	
	public void updateCouponStatus(long userId,int couponId,int status) throws Exception {
		couponDAO.updateStatus(userId, couponId, status);
	}
	
	public List<Coupon> getAllCoupons(int size) throws Exception{
		return couponDAO.getAllCoupons(size);
	}
}
